package com.qf.shixi.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.qf.shixi.dao.OrderDao;
import com.qf.shixi.entity.Order;
import com.qf.shixi.service.OrderService;
import com.qf.shixi.util.SendSms;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * (Order)表服务实现类
 *
 * @author
 * @since 2021-10-11 16:33:13
 */
@Service("orderService")
public class OrderServiceImpl implements OrderService {

    Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Resource
    private OrderDao orderDao;

    /**
     * 通过ID查询单条数据
     *
     * @param oId 主键
     * @return 实例对象
     */
    @Override
    public Order queryById(Integer oId) {
        return this.orderDao.queryById(oId);
    }


    @Override
    public Order insert(Order order) {


        this.orderDao.insert(order);


        return order;
    }

    /**
     * 修改数据
     *
     * @param order 实例对象
     * @return 实例对象
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean update(Order order) {
        int i = orderDao.update(order);
        if(i > 0){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 通过主键删除数据
     *
     * @param oId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer oId) {
        return this.orderDao.deleteById(oId) > 0;
    }

    /**
     * 阿里云的短信平台接入
     * 事务的处理----事务回滚(try-catch滥用)
     * 全局异常处理
     *
     * @param order
     * @return 事务只有在程序抛出运行时异常或者Error错误的时候才会自动回滚   sqlException
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String order(Order order) throws Exception{
        //先发送短信
        String code = SendSms.Sms(order.getTel());
        if (code == null) {
            return "短信发送异常";
        }
        //将记录添加到数据库中
        // 提交时间   状态需要默认设置    验证码
        order.setSubtime(new Date());
        order.setStatus(0);
        order.setCode(code);
        int i = orderDao.insert(order);
        return "success";
    }

    @Override
    public List<Order> queryAll() {
        List<Order> orders = orderDao.queryAll();
        return orders;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean deleteByIds(JSONArray idArr) {
        Integer i = orderDao.deleteByIds(idArr);
        if(i>0){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public List<Order> queryByConditions(Order order) {
        List<Order> orders =  orderDao.queryByConditions(order);
        return orders;
    }


}
